package com.ashin.util;

import it.sauronsoftware.jave.AudioUtils;
import ws.schild.jave.Encoder;
import ws.schild.jave.EncoderException;
import ws.schild.jave.InputFormatException;
import ws.schild.jave.MultimediaObject;
import ws.schild.jave.encode.AudioAttributes;
import ws.schild.jave.encode.EncodingAttributes;

import java.io.File;

public class MP3ToSILKConverter {
    public static void main(String[] args) {
        // 原始MP3文件路径
        String mp3FilePath = "data/voice/1698724715493.mp3";
        // 日标SILK文件输出路径
        String silkFilePath = "data/output.pcm";

        File sourceFile = new File(mp3FilePath);//输入
        File targetFile = new File("data/output.amr");//输出
        AudioUtils.amrToMp3(sourceFile, targetFile);//转换
        try {

            // 创建转换器
            AudioAttributes audioAttributes = new AudioAttributes();
            audioAttributes.setCodec("pcm_s16le");
            audioAttributes.setChannels(1);
            audioAttributes .setBitRate(24000);
            audioAttributes.setSamplingRate(24);
            EncodingAttributes encodingAttributes = new EncodingAttributes();
            encodingAttributes.setOutputFormat("pcm");
            encodingAttributes.setInputFormat("mp3");
            encodingAttributes.setAudioAttributes(audioAttributes);
            Encoder encoder = new Encoder();
            // 进行转换
            File mp3File = new File(mp3FilePath);
            File silkFile = new File(silkFilePath);
            encoder.encode(new MultimediaObject(mp3File), silkFile, encodingAttributes);
            System.out.println("MP3转SILK转换成功!");
        }
        catch (InputFormatException e) {
            throw new RuntimeException(e);
        } catch (EncoderException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 音频转换为mp3格式，audioPath可更换为要转换的音频格式
     * @param audioPath
     * @param mp3Path
     */
    public static void toMp3(String audioPath,String mp3Path){
        File source = new File(audioPath);
        File target = new File(mp3Path);
        AudioAttributes audio = new AudioAttributes();
        audio.setCodec("libmp3lame");
        audio.setBitRate(128000);
        audio.setChannels(2);
        audio.setSamplingRate(44100);

        EncodingAttributes attrs = new EncodingAttributes();
        attrs.setOutputFormat("mp3");
        attrs.setAudioAttributes(audio);
        Encoder encoder = new Encoder();
        try {
            encoder.encode(new MultimediaObject(source), target, attrs);
        } catch (EncoderException e) {
            e.printStackTrace();
        }
    }
}

